package com.shigu.advert.action;

import com.shigu.MallResponse;
import com.shigu.PageResponse;
import com.shigu.advert.api.AdvertService;
import com.shigu.advert.bo.*;
import com.shigu.advert.vo.AdvertVo;
import com.shigu.exceptions.AdminException;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.validation.Valid;

/*
 * create by  过儿  2019-06-11
 * 轮播广告图
 */
@RequestMapping("adminjson")
@Controller
public class AdvertController {

    @Resource(name = "advertServiceImpl")
    AdvertService advertService;

    @RequestMapping("advertList")
    @ResponseBody
    public PageResponse<AdvertVo> advertList(AdvertListRequest request) {
        return advertService.advertList(request.getPage(), request.getSize(), request.getItemCode(),request.getCid());
    }

    @RequestMapping("addAdvert")
    @ResponseBody
    public MallResponse addAdvert(AddAdvertRequest request) throws AdminException {
        AdvertBo bo = new AdvertBo();
        bo.setItemId(request.getItemId());
        bo.setImgUrl(request.getImgUrl());
        if(StringUtils.isNotBlank(request.getCid())){
            bo.setCid(Long.valueOf(request.getCid()));
        }
        bo.setWeight(request.getWeight());
        advertService.addAdvert(bo);
        return new MallResponse().success();
    }

    @RequestMapping("deleteAdvert")
    @ResponseBody
    public MallResponse deleteAdvert(AdvertRequest request){
        advertService.delAdvert(Long.valueOf(request.getAdvertId()));
        return new MallResponse().success();
    }

    @RequestMapping("modifyAdvert")
    @ResponseBody
    public MallResponse modifyAdvert(@Valid ModifyAdvertRequest request, BindingResult result) throws AdminException {
        if(result.hasErrors()){
            throw new AdminException(result.getFieldError().getDefaultMessage());
        }
        //转换为bo
        ModifyAdvertBo bo = new ModifyAdvertBo();
        bo.setAdvertId(Long.valueOf(request.getAdvertId()));
        if(StringUtils.isNotBlank(request.getCid())){
            bo.setCid(Long.valueOf(request.getCid()));
        }
        if(StringUtils.isNotBlank(request.getImgUrl())){
            bo.setImgUrl(request.getImgUrl());
        }
        if(StringUtils.isNotBlank(request.getRemark())){
            bo.setRemark(request.getRemark());
        }
        if(StringUtils.isNotBlank(request.getItemId())){
            bo.setItemId(Long.valueOf(request.getItemId()));
        }
        bo.setWeight(request.getWeight());

        advertService.modifyAdvert(bo);
        return new MallResponse().success();
    }

}
